package tyk.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
@Aspect
public class MyAspect {

    @Pointcut("execution(* tyk.aop.UserService.*(..))")
    public void pc(){}

    @Before("pc()")
    public void qz(JoinPoint joinPoint) {
        System.out.println(getTime()+" XX 正在执行 "+joinPoint.getSignature().getName()+"方法");
        System.out.println("前置通知：,方法名："+joinPoint.getSignature().getName()+",参数："+joinPoint.getArgs());
    }

    @Before("pc()")
    public void hz(JoinPoint joinPoint) {
        System.out.println("后置通知：,方法名："+joinPoint.getSignature().getName()+",参数："+joinPoint.getArgs());
    }

    @Around("pc()")
    public Object hr(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕方法：调用方法前,方法名："+pjp.getSignature().getName()+",参数："+pjp.getArgs());
        Object result = pjp.proceed();
        System.out.println("环绕方法：调用方法后,结果result="+result);
        return result;
    }

    @AfterReturning(value = "pc()",returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[debug]返回通知，方法名："+methodName+"，结果："+result);
    }

    @AfterThrowing(value = "pc()", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("[debug]异常通知，方法名："+methodName+"，异常："+ex);
    }

    public String getTime(){
        // 获取当前的日期和时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义日期时间格式（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间为指定格式的字符串（可选）
        return currentTime.format(formatter);
    }
}
